#!/usr/bin/python3
# coding=utf-8

# -----------------------------------
# Author: bobo
# Date: 20238.20
# -----------------------------------
"""docker-save.
Usage:
    docker-save.py bak [--bakdir=<path>]
    docker-save.py bak [--bakdir=<path>] (-c | --cover)
    docker-save.py load <image>
    docker-save.py (-h | --help)
    docker-save.py --version

Options:
    -h --help   Show info.
    -c --cover  Cover exist bak file.
    --version  Show version.
    --bakdir=<path>  Backup path.
"""

import os

from docopt import docopt

BAK_DIR = "/mnt/disk2/dup_bak/docker-image"


def get_image_list():
    """
    获取镜像列表
    :param num1: null
    :return: image list
    """
    tmp_img_lst = []
    cmd = "docker image ls"
    resut = os.popen(cmd).read().strip()
    imgs = resut.split("\n")[1:]
    for img in imgs:
        img = img.split()
        # print(img)
        tmp_img_lst.append(img[0] + ":" + img[1])
    return tmp_img_lst


def export_image(image_lst, bak_dir="", cover=False):
    """
    备份镜像
    :param image_lst: 镜像列表
    :return: 0 success
    """
    cmd_fmt = r"docker save {0} | gzip > {1}"
    if bak_dir is None:
        # print("-----", bak_dir)
        bak_dir = BAK_DIR
    if cover is True:
        print("----- cover exist bakckup file")

    for img in image_lst:
        bak_file = img.replace("/", "#") + ".tar.gz"
        bak_full_file = os.path.join(bak_dir, bak_file)

        if (not cover) and os.path.exists(bak_full_file):
            print(f"image: {bak_file} already exist.")
            continue
        print(f"backup image: {img} to {bak_dir}...")
        result = os.system(cmd_fmt.format(img, bak_full_file))
        # result = 0
        if result != 0:
            print(f"Error: backup image {img} failed.")
            os.system(f"rm -f {bak_full_file}")
            return 1
    return 0


if __name__ == "__main__":
    # print(__doc__)
    arguments = docopt(__doc__, version="docker-save 1.0")
    # print(arguments)
    if arguments.get("bak"):
        print("开始导出docker镜像")
        img_lst = get_image_list()
        # print('image list:',img_lst)
        export_image(img_lst, arguments.get("--bakdir"),
                     arguments.get("--cover"))
    elif arguments.get("load"):
        image = arguments.get("<image>")
        if os.path.exists(image):
            print(f"load image {image}")
            # print("gunzip -c {} | docker load".format(image))
            os.system(f"gunzip -c {image} | docker load")
        else:
            print(f"image[{image}] not exist.")
    else:
        print(__doc__)
